/*
 * @Date: 2022-06-19 15:59:35
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-06-25 15:22:09
 * @FilePath: \my-taro-app\src\components\Lyrics\index.tsx
 * @Description: 歌词
 */
import { View, ScrollView } from "@tarojs/components";
import React, { useEffect, useState } from "react";
import classNames from "classnames";
import "./index.scss";
import Taro from "@tarojs/taro";
import { useSelector } from "@/store/hooks";
import { useDispatch } from "react-redux";

export interface ILyrics {
  propLyrArr: Array<{ t: number; content: string }>;
  CurrentLyricIndex: number;
}
const index: React.FC<ILyrics> = ({ propLyrArr, CurrentLyricIndex }) => {
  const [scroll, setScroll] = useState(0);
  const [placeholderHeight, setPlaceholderHeight] = useState(0);
  const [lyricArr, setLyricArr] = useState<any>([]);
  const { CurrentSongState } = useSelector(state => ({
    CurrentSongState: state.PlaySong
  }));

  useEffect(() => {
    setLyricArr([]);
    setScroll(0);
  }, [CurrentSongState.timeStamp]);

  useEffect(() => {
    Taro.nextTick(() => {
      const query = Taro.createSelectorQuery();
      query.selectAll(".lyric-item").boundingClientRect();
      query.select(".lyrics-show-area").boundingClientRect();
      query.exec(function(res) {
        let distance;
        const [lyricsArr, lyrics] = res;
        //由于每次更新之后歌词数组的top值都会变化导致计算出现问题，这里只对第一次获取数组进行保存计算
        if (lyricArr.length === 0) {
          setLyricArr(lyricsArr);
        } else {
          if (placeholderHeight === 0) {
            setPlaceholderHeight(lyricArr[0].top - lyrics.top);
          }
          if (lyricArr[CurrentLyricIndex - 1]) {
            distance =
              lyricArr[CurrentLyricIndex - 1].top -
              lyrics.top -
              placeholderHeight;
            setScroll(distance);
          }
        }
      });
    });
  }, [CurrentLyricIndex]);

  return (
    <View id="lyrics-container-unique">
      <ScrollView
        className="lyrics-show-area"
        scrollY
        scrollTop={scroll}
        scrollWithAnimation
      >
        <View className="placeholder"></View>
        {propLyrArr.map((item, index) => {
          return (
            <View
              className={classNames({
                "lyric-item": true,
                "current-lyric": CurrentLyricIndex === index
              })}
              key={item.t + item.content}
            >
              {item.content}
            </View>
          );
        })}
        <View className="placeholder"></View>
      </ScrollView>
    </View>
  );
};
export default index;
